/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package kimo.persistence.controllers;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import kimo.persistence.entities.ProductType;
import kimo.persistence.entities.Production;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import kimo.persistence.controllers.exceptions.IllegalOrphanException;
import kimo.persistence.controllers.exceptions.NonexistentEntityException;
import kimo.persistence.entities.Product;

/**
 *
 * @author a381u296
 */
public class ProductJpaController implements Serializable {

    public ProductJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Product product) {
        if (product.getProductionList() == null) {
            product.setProductionList(new ArrayList<Production>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            ProductType productTypeId = product.getProductTypeId();
            if (productTypeId != null) {
                productTypeId = em.getReference(productTypeId.getClass(), productTypeId.getProductTypeId());
                product.setProductTypeId(productTypeId);
            }
            List<Production> attachedProductionList = new ArrayList<Production>();
            for (Production productionListProductionToAttach : product.getProductionList()) {
                productionListProductionToAttach = em.getReference(productionListProductionToAttach.getClass(), productionListProductionToAttach.getProductionId());
                attachedProductionList.add(productionListProductionToAttach);
            }
            product.setProductionList(attachedProductionList);
            em.persist(product);
            if (productTypeId != null) {
                productTypeId.getProductList().add(product);
                productTypeId = em.merge(productTypeId);
            }
            for (Production productionListProduction : product.getProductionList()) {
                Product oldProductionProductIdOfProductionListProduction = productionListProduction.getProductionProductId();
                productionListProduction.setProductionProductId(product);
                productionListProduction = em.merge(productionListProduction);
                if (oldProductionProductIdOfProductionListProduction != null) {
                    oldProductionProductIdOfProductionListProduction.getProductionList().remove(productionListProduction);
                    oldProductionProductIdOfProductionListProduction = em.merge(oldProductionProductIdOfProductionListProduction);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Product product) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Product persistentProduct = em.find(Product.class, product.getProductId());
            ProductType productTypeIdOld = persistentProduct.getProductTypeId();
            ProductType productTypeIdNew = product.getProductTypeId();
            List<Production> productionListOld = persistentProduct.getProductionList();
            List<Production> productionListNew = product.getProductionList();
            List<String> illegalOrphanMessages = null;
            for (Production productionListOldProduction : productionListOld) {
                if (!productionListNew.contains(productionListOldProduction)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Production " + productionListOldProduction + " since its productionProductId field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (productTypeIdNew != null) {
                productTypeIdNew = em.getReference(productTypeIdNew.getClass(), productTypeIdNew.getProductTypeId());
                product.setProductTypeId(productTypeIdNew);
            }
            List<Production> attachedProductionListNew = new ArrayList<Production>();
            for (Production productionListNewProductionToAttach : productionListNew) {
                productionListNewProductionToAttach = em.getReference(productionListNewProductionToAttach.getClass(), productionListNewProductionToAttach.getProductionId());
                attachedProductionListNew.add(productionListNewProductionToAttach);
            }
            productionListNew = attachedProductionListNew;
            product.setProductionList(productionListNew);
            product = em.merge(product);
            if (productTypeIdOld != null && !productTypeIdOld.equals(productTypeIdNew)) {
                productTypeIdOld.getProductList().remove(product);
                productTypeIdOld = em.merge(productTypeIdOld);
            }
            if (productTypeIdNew != null && !productTypeIdNew.equals(productTypeIdOld)) {
                productTypeIdNew.getProductList().add(product);
                productTypeIdNew = em.merge(productTypeIdNew);
            }
            for (Production productionListNewProduction : productionListNew) {
                if (!productionListOld.contains(productionListNewProduction)) {
                    Product oldProductionProductIdOfProductionListNewProduction = productionListNewProduction.getProductionProductId();
                    productionListNewProduction.setProductionProductId(product);
                    productionListNewProduction = em.merge(productionListNewProduction);
                    if (oldProductionProductIdOfProductionListNewProduction != null && !oldProductionProductIdOfProductionListNewProduction.equals(product)) {
                        oldProductionProductIdOfProductionListNewProduction.getProductionList().remove(productionListNewProduction);
                        oldProductionProductIdOfProductionListNewProduction = em.merge(oldProductionProductIdOfProductionListNewProduction);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = product.getProductId();
                if (findProduct(id) == null) {
                    throw new NonexistentEntityException("The product with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Product product;
            try {
                product = em.getReference(Product.class, id);
                product.getProductId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The product with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Production> productionListOrphanCheck = product.getProductionList();
            for (Production productionListOrphanCheckProduction : productionListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Product (" + product + ") cannot be destroyed since the Production " + productionListOrphanCheckProduction + " in its productionList field has a non-nullable productionProductId field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            ProductType productTypeId = product.getProductTypeId();
            if (productTypeId != null) {
                productTypeId.getProductList().remove(product);
                productTypeId = em.merge(productTypeId);
            }
            em.remove(product);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Product> findProductEntities() {
        return findProductEntities(true, -1, -1);
    }

    public List<Product> findProductEntities(int maxResults, int firstResult) {
        return findProductEntities(false, maxResults, firstResult);
    }

    private List<Product> findProductEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Product.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Product findProduct(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Product.class, id);
        } finally {
            em.close();
        }
    }

    public int getProductCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Product> rt = cq.from(Product.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
